<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :need-return="false"
      :btn-list="fullInfo.btnList"
    >
      <template v-slot:full-button>
        <ScanInputBox
          :query="scanInfo.query"
          :api="scanInfo.api"
          style="margin-right: 10px"
          :disabled="!formInfo.data.supplierName"
          :deptFlag="false"
          :table-data="tableInfo.data"
          @callback="onCallBackScanData"
        />
      </template>
      <!-- 主表信息 -->
      <div id="table-list">
        <div class="model-panel">
          <el-collapse v-model="activeNames">
            <el-collapse-item name="1">
              <template #title>
                <div class="model-panel-title">
                  <p>{{ $t('basic_information') }}</p>
                </div>
              </template>
              <div class="model-panel-body">
                <!-- form -->
                <page-form
                  class="paddingBox order-model-formBox flex_wrap_start_start"
                  v-model:ref-obj="formInfo.ref"
                  :disabled="formInfo.disabled"
                  :data="formInfo.data"
                  :field-list="formInfo.fieldList"
                  :rules="formInfo.rules"
                  :label-width="formInfo.labelWidth"
                  @handleEvent="handleFormEvent"
                >
                  <template v-slot:form-supplierName>
                    <el-input
                      v-model="formInfo.data.supplierName"
                      :class="!orderId ? 'not-mongolia' : ''"
                      type="input"
                      placeholder="请选择供应商"
                      :disabled="true"
                    >
                      <template v-if="!orderId" #append>
                        <el-icon @click="openSupplier"><MoreFilled /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:form-depotName>
                    <el-input
                      v-model="formInfo.data.depotName"
                      class="not-br not-mongolia"
                      type="input"
                      :disabled="true"
                      placeholder="请选择仓库"
                    >
                      <template #append>
                        <el-icon @click="openDepotWindow"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:form-purchDeptName>
                    <el-input
                      class="not-mongolia"
                      type="input"
                      placeholder="请选择采购部门"
                      :disabled="true"
                      v-model="formInfo.data.purchDeptName"
                    >
                      <template #append>
                        <el-icon @click="selectPurchDept"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:form-receiveAddressValue>
                    <el-input
                      v-model="formInfo.data.receiveAddressValue"
                      class="not-mongolia"
                      type="input"
                      :disabled="true"
                      placeholder="请选择收货地址"
                    >
                      <template #append>
                        <el-icon @click="openReceiveAddressWindow"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:form-filePathList>
                    <upload-img
                      v-model:value="formInfo.data.filePathList"
                      multiple
                      :action="action"
                      :limit="10"
                      :title="`附件`"
                      :responseFn="handleResponse"
                    />
                  </template>
                </page-form>
              </div>
            </el-collapse-item>
          </el-collapse>
          <!-- 明细信息 -->
          <div id="table-box" class="model-panel">
            <div class="model-panel-title">
              <Tooltip :text="$t('detailInfo')"></Tooltip>
            </div>
            <div class="model-panel-body">
              <!-- 条件栏 -->
              <NewPageFilter :filter-btn="filterInfo.btnList">
                <template v-slot:filter-addProduct>
                  <el-button
                    :disabled="!formInfo.data.supplierName"
                    @click="addProduct"
                    >添加产品</el-button
                  >
                </template>
                <template v-slot:filter-remove>
                  <el-button
                    :disabled="!tableInfo.selections.length"
                    @click="remove"
                  >
                    删除产品
                  </el-button>
                </template>

                <template v-slot:filter-fillTem>
                  <el-input-number
                    v-model="filterInfo.data.tem"
                    controls-position="right"
                    style="width: 100px"
                    placeholder="温度"
                    :step="1"
                    :min="-100"
                    :max="100"
                  />
                  <el-button @click="changeNumberTemHum('tem')"
                    >温度设置</el-button
                  >
                </template>
                <template v-slot:filter-fillHum>
                  <el-input-number
                    v-model="filterInfo.data.hum"
                    controls-position="right"
                    style="width: 100px"
                    :min="0"
                    :max="100"
                    placeholder="湿度"
                    :precision="0"
                    :step="1"
                  >
                    <template #append>.com</template>
                  </el-input-number>
                  <el-button @click="changeNumberTemHum('hum')"
                    >湿度设置</el-button
                  >
                </template>
                <template v-slot:filter-packageMark>
                  <el-select
                    v-model.lazy="filterInfo.data.packageMark"
                    style="width: 130px"
                    placeholder="选择包装标识"
                    clearable
                    @change="changeSelectAll($event, 'package_mark')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'package_mark'
                      ]"
                      :key="index"
                      class="option"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-identifyMark>
                  <el-select
                    v-model.lazy="filterInfo.data.identifyMark"
                    clearable
                    style="width: 130px"
                    placeholder="选择确定标识"
                    @change="changeSelectAll($event, 'identify_mark')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'identify_mark'
                      ]"
                      :key="index"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-certificateMark>
                  <el-select
                    v-model.lazy="filterInfo.data.certificateMark"
                    clearable
                    style="width: 130px"
                    placeholder="选择证书标识"
                    @change="changeSelectAll($event, 'certificate_mark')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'certificate_mark'
                      ]"
                      :key="index"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-appearanceQuality>
                  <el-select
                    v-model.lazy="filterInfo.data.appearanceQuality"
                    clearable
                    style="width: 130px"
                    placeholder="选择外观质量"
                    @change="changeSelectAll($event, 'appearance_quality')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'appearance_quality'
                      ]"
                      :key="index"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-invalidReason>
                  <el-select
                    v-model.lazy="filterInfo.data.invalidReason"
                    clearable
                    style="width: 130px"
                    placeholder="选择不合格原因"
                    @change="changeSelectAll($event, 'invalid_reason')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'invalid_reason'
                      ]"
                      :key="index"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-receiptNumber>
                  <el-input
                    v-model="filterInfo.data.receiptNumber"
                    style="width: 100px"
                    placeholder="发票号"
                    :maxlength="50"
                  />
                  <el-button @click="batchHandle()">发票号设置</el-button>
                </template>
              </NewPageFilter>
              <!-- 表格 -->
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data.async="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :index-method="indexMethod"
                  :check-box="true"
                  :query="filterInfo.query"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-batchNumber="scope">
                    <el-input
                      v-model="scope.row.batchNumber"
                      :maxlength="25"
                      @change="changeData($event, scope.row, scope.$index)"
                      @input="(e) => (scope.row.batchNumber = validSe(e))"
                    />
                  </template>
                  <template v-slot:col-productionDate="scope">
                    <el-date-picker
                      v-model="scope.row.productionDate"
                      value-format="YYYY-MM-DD"
                      :disabled-date="productionTimePickerOptions.disabledDate"
                      @change="changeData($event, scope.row, scope.$index)"
                    />
                  </template>
                  <template v-slot:col-validityDate="scope">
                    <el-date-picker
                      v-model="scope.row.validityDate"
                      value-format="YYYY-MM-DD"
                      :disabled-date="validityTimePickerOptions.disabledDate"
                      @change="changeData($event, scope.row, scope.$index)"
                    />
                  </template>
                  <template v-slot:col-qty="scope">
                    <el-form-item
                      v-if="scope.row.qtyOperateMode !== 3"
                      class="margin-bottom"
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              v-if="scope.$index >= 0"
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positive,
                                        trigger: ['blur', 'change'],
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                v-model.lazy="scope.row.largeUnitQty"
                                style="width: 100%; margintop: 18px"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                :min="0"
                                :max="largeMax(scope.row)"
                                @change="
                                  changeLarge(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                            class="page-table-input-number-item"
                          >
                            <el-form-item v-if="scope.$index >= 0">
                              <el-input-number
                                v-model.lazy="scope.row.smallUnitQty"
                                style="width: 100%; margintop: 18px"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="smallMax(scope.row)"
                                @change="changeSmall($event, scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          v-if="scope.row.qtyOperateMode === 2"
                          class="page-table-input-number-right"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                    <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                  </template>
                  <template v-slot:col-price="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}[price]`"
                      :rules="
                        scope.$index >= 0
                          ? {
                              validator: $validate.positiveMoneyZero,
                              trigger: 'blur',
                            }
                          : {}
                      "
                    >
                      <el-input-number
                        v-model="scope.row.price"
                        controls-position="right"
                        style="minwidth: 100px; margintop: 18px"
                        :precision="systemConfig.price_precision"
                        :step="1"
                        :min="0"
                        :max="999999999999999"
                        @change="
                          changePrice($event, `data.${scope.$index}.price`)
                        "
                      />
                      <p
                        style="color: red"
                        v-if="
                          scope.row.isLimitPrice == 1 &&
                          scope.row.price > scope.row.purchaseLimitPrice
                        "
                      >
                        超过产品限价:{{ scope.row.purchaseLimitPrice }}
                      </p>
                    </el-form-item>
                  </template>
                  <template v-slot:col-tem="scope">
                    <el-input-number
                      v-model="scope.row.tem"
                      controls-position="right"
                      style="width: 100px"
                      :step="1"
                    />
                  </template>
                  <template v-slot:col-hum="scope">
                    <el-input-number
                      v-model="scope.row.hum"
                      controls-position="right"
                      style="width: 100px"
                      :min="0"
                      :max="100"
                      :precision="0"
                      :step="1"
                    />
                  </template>

                  <template v-slot:col-packageMarkValue="scope">
                    <el-select
                      v-model.lazy="scope.row.packageMarkValue"
                      style="width: 100%"
                      placeholder="选择包装标识"
                      clearable
                    >
                      <el-option
                        v-for="(item, index) in $store.state.permission.dict[
                          'package_mark'
                        ]"
                        :key="index"
                        class="option"
                        :value="item.code"
                        :label="item.name"
                      ></el-option>
                    </el-select>
                  </template>
                  <template v-slot:col-identifyMarkValue="scope">
                    <el-select
                      v-model.lazy="scope.row.identifyMarkValue"
                      style="width: 100%"
                      placeholder="选择确定标识"
                      clearable
                    >
                      <el-option
                        v-for="(item, index) in $store.state.permission.dict[
                          'identify_mark'
                        ]"
                        :key="index"
                        class="option"
                        :value="item.code"
                        :label="item.name"
                      ></el-option>
                    </el-select>
                  </template>
                  <template v-slot:col-certificateMarkValue="scope">
                    <el-select
                      v-model.lazy="scope.row.certificateMarkValue"
                      style="width: 100%"
                      placeholder="选择证书标识"
                      clearable
                    >
                      <el-option
                        v-for="(item, index) in $store.state.permission.dict[
                          'certificate_mark'
                        ]"
                        :key="index"
                        class="option"
                        :value="item.code"
                        :label="item.name"
                      ></el-option>
                    </el-select>
                  </template>
                  <template v-slot:col-appearanceQualityValue="scope">
                    <el-select
                      v-model.lazy="scope.row.appearanceQualityValue"
                      style="width: 100%"
                      placeholder="选择外观质量"
                      clearable
                    >
                      <el-option
                        v-for="(item, index) in $store.state.permission.dict[
                          'appearance_quality'
                        ]"
                        :key="index"
                        class="option"
                        :value="item.code"
                        :label="item.name"
                      ></el-option>
                    </el-select>
                  </template>
                  <template v-slot:col-invalidReasonValue="scope">
                    <el-select
                      v-model.lazy="scope.row.invalidReasonValue"
                      style="width: 100%"
                      placeholder="选择不合格原因"
                      clearable
                    >
                      <el-option
                        v-for="(item, index) in $store.state.permission.dict[
                          'invalid_reason'
                        ]"
                        :key="index"
                        class="option"
                        :value="item.code"
                        :label="item.name"
                      ></el-option>
                    </el-select>
                  </template>
                  <template v-slot:col-receiptNumber="scope">
                    <el-input
                      v-if="
                        formInfo.data.isEstimationStockBusiness != 1 &&
                        formInfo.data.isConsignBusiness !== '1'
                          ? formInfo.data.isConsignBusiness === '0'
                            ? true
                            : scope.row.isConsignment == 0
                          : false
                      "
                      v-model="scope.row.receiptNumber"
                      @input="receiptNumberChange($event, scope.$index)"
                      :maxlength="50"
                    ></el-input>
                    <span v-else>{{ scope.row.receiptNumber || '-' }}</span>
                  </template>
                  <template v-slot:col-receiptPrice="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}[receiptPrice]`"
                      v-if="
                        formInfo.data.isEstimationStockBusiness != 1 &&
                        formInfo.data.isConsignBusiness !== '1'
                          ? formInfo.data.isConsignBusiness === '0'
                            ? true
                            : scope.row.isConsignment == 0
                          : false
                      "
                    >
                      <el-input-number
                        v-model="scope.row.receiptPrice"
                        controls-position="right"
                        style="minwidth: 100px; margintop: 18px"
                        :precision="systemConfig.price_precision"
                        :step="1"
                        :min="0"
                        :max="999999999999999"
                        @change="
                          changePrice(
                            $event,
                            `data.${scope.$index}.receiptPrice`
                          )
                        "
                      />
                    </el-form-item>
                    <span v-else>{{ scope.row.receiptPrice || '-' }}</span>
                  </template>
                  <template v-slot:col-receiptCalcQty="scope">
                    <el-form-item
                      v-if="
                        formInfo.data.isEstimationStockBusiness != 1 &&
                        formInfo.data.isConsignBusiness !== '1'
                          ? formInfo.data.isConsignBusiness === '0'
                            ? true
                            : scope.row.isConsignment == 0
                          : false
                      "
                      :prop="`data.${scope.$index}.receiptCalcQty`"
                    >
                      <el-input-number
                        v-model.lazy="scope.row.receiptCalcQty"
                        style="width: 100%; margintop: 18px"
                        clearable
                        controls-position="right"
                        :precision="systemConfig.qty_show_precision"
                        :min="0"
                        :max="scope.row.qty"
                      />
                    </el-form-item>
                    <span v-else>{{ scope.row.receiptCalcQty || '-' }}</span>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!-- 仓库选择框 -->
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :query="selectDepotInfo.query"
      :check-box="false"
      :highlight-row="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
    <!-- 选择收货地址 -->
    <select-receive-address
      v-if="selectReceiveAddressInfo.visible"
      v-model:show-dialog="selectReceiveAddressInfo.visible"
      :query="selectReceiveAddressInfo.query"
      :check-box="false"
      :highlight-row="true"
      @callback="selectReceiveAddressCallback"
    />
    <!--选择产品-->
    <SelectSupplierProduct
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      :query="productInfo.query"
      @callback="selectProduct"
    />
    <!-- 选择供应商 -->
    <SelectReceivingSupplier
      v-if="supplierInfo.visible"
      v-model:visible="supplierInfo.visible"
      @callback="callBackSupplier"
    />
    <!-- <SelectSupplier
      v-if="supplierInfo.visible"
      v-model:showDialog="supplierInfo.visible"
      v-model:query="supplierInfo.query"
      :checkBox="false"
      :highlightRow="true"
      @callback="callBackSupplier"
    /> -->
    <select-dept
      v-if="selectDeptInfo.visible"
      v-model:show-dialog="selectDeptInfo.visible"
      :query="selectDeptInfo.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectDeptCallback"
    />
  </div>
</template>

<script setup name="receivingModify">
const SelectDepotStorage = defineAsyncComponent(() => import('./selectProduct'))
const ScanInputBox = defineAsyncComponent(() =>
  import('@/views/stock/otherStore/ScanInputBox')
)
const SelectSupplierProduct = defineAsyncComponent(() =>
  import('./selectSupplierProduct')
)
const SelectReceivingSupplier = defineAsyncComponent(() =>
  import('./selectReceivingSupplier')
)

import {
  getReceivingsScans,
  getReceivingOrderById,
  batchValidateReceivingOrder,
  receivingDetailsCustomizeListAll,
  handAddReceivings,
  handAddReceivingsAndSave,
  validateReceivingOrderNums,
} from '@/api/stock'
import {
  getDepotsDefault,
  postPrintQrCodeScanForInBound,
  getReceiveAddressPage,
} from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
import _ from 'lodash'
import axios from 'axios'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
import { watch } from 'vue'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const loading = ref(false)
const scrollTop = ref(0)
const box = ref(undefined)

const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  orderId: {
    type: [Number, String],
  },
})
const activeNames = ref(['1'])
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formRefs = ref([])
const scanInfo = reactive({
  api: postPrintQrCodeScanForInBound,
  query: {
    supplierId: '',
  },
})
//full组件信息
const fullInfo = reactive({
  visible: false,
  btnList: [
    {
      label: '保存并提交',
      event: saveAndSubmit,
      show: !props.orderId && proxy.$permission('receiving:saveAndSubmit'),
      loading: false,
    },
    { label: '保存', event: save, show: true, loading: false },
    { label: '返回', event: returnBank, show: true },
  ],
})
const formInfo = reactive({
  ref: null,
  data: {
    isEstimationStockBusiness: 0,
    conclusion: '合格',
  },
  fieldList: [
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
    },
    { label: '仓库', value: 'depotName', type: 'slot' },
    { label: '部门', value: 'deptName', type: 'input', disabled: true },
    { label: '收货地址', value: 'receiveAddressValue', type: 'slot' },

    {
      label: '收货联系人',
      value: 'receivingContacts',
      type: 'input',
    },
    {
      label: '联系人电话',
      value: 'receivingPhone',
      type: 'input',
    },
    // {
    //   label: '货单号',
    //   value: 'waybillNumber',
    //   type: 'input',
    // },
    {
      label: '是否寄售业务',
      value: 'isConsignBusiness',
      type: 'select-model',
      code: 'yes_or_no',
      event: 'isConsignBusiness',
      labelTip: '为空时，根据产品属性自动拆分为寄售和非寄售',
      clearable: true,
      checkDefault: false,
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
      disabled: props.orderId ? true : false,
    },
    // {
    //   label: '是否暂估入库',
    //   value: 'isEstimationStockBusiness',
    //   type: 'select-model',
    //   code: 'default_no_or_yes',
    //   event: 'isEstimationStockBusiness',
    //   show:
    //     proxy.$store.state.permission.systemConfig
    //       .is_estimation_stock_business == 1,
    //   disabled: props.orderId ? true : false,
    // },
    {
      label: '采购部门',
      value: 'purchDeptName',
      type: 'slot',
    },
    {
      label: '验收结论',
      value: 'conclusion',
      type: 'textarea',
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    {
      label: '发票号汇总',
      value: 'receiptNumber',
      type: 'input',
      disabled: true,
    },
    {
      label: '发票总金额',
      value: 'receiptSumAmount',
      type: 'input',
      disabled: true,
    },
    {
      label: '配送方式',
      value: 'deliveryType',
      type: 'select-model',
      code: 'delivery_type',
      clearable: true,
    },
    {
      label: '配送人',
      value: 'deliveryUser',
      type: 'input',
    },
    {
      label: '配送人电话',
      value: 'deliveryPhone',
      type: 'input',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
    {
      label: '附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    supplierName: [
      { required: true, message: '请选择供应商', target: 'change' },
    ],
    depotName: [{ required: true, message: '请选择仓库', target: 'change' }],
    deptName: [{ required: true, message: '请输入部门', target: 'blur' }],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
    receivingPhone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  btnList: [
    { label: '添加产品', type: 'slot', value: 'addProduct' },
    { label: '删除产品', type: 'slot', value: 'remove' },
    { label: '温度填充', type: 'slot', value: 'fillTem' },
    { label: '湿度填充', type: 'slot', value: 'fillHum' },
    { label: '包装标识', type: 'slot', value: 'packageMark' },
    { label: '确定标识', type: 'slot', value: 'identifyMark' },
    { label: '合格证', type: 'slot', value: 'certificateMark' },
    { label: '外观质量', type: 'slot', value: 'appearanceQuality' },
    { label: '不合格原因值', type: 'slot', value: 'invalidReason' },
    {
      type: 'slot',
      value: 'receiptNumber',
      label: '一键设置发票号',
    },
  ],
  data: {
    hum: 0,
    tem: 0,
    packageMark: '',
    identifyMark: '',
    certificateMark: '',
    appearanceQuality: '',
    invalidReason: '',
    receiptNumber: '',
  },
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'deliverQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'pendReceiveQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  batchNumberRules: [
    { required: true, message: '请输入批号', target: 'blur' },
    { required: true, message: '请输入批号', target: 'change' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '140',
    btList: [
      {
        label: '复制行',
        event: addBatchNumber,
        show: true,
        ifRender: function (row) {
          return row.codeType !== 3
        },
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: remove,
        show: proxy.$permission('receiving:del'),
      },
    ],
  },
})
const selectDepotInfo = reactive({
  visible: false,
  query: {
    status: '1',
    sort: 'create_time desc',
    depotAuth: 'id',
    useTypeId: '1',
    isCargoSpaceManage: '',
  },
})
let productInfo = reactive({
  visible: false,
  query: {
    productIdNotIn: '',
    supplierId: '',
    codeTypeNotIn: 3,
    putShelfStatus: 1,
    productStatus: 1,
  },
})
const supplierInfo = reactive({
  visible: false,
})
const selectDeptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const selectReceiveAddressInfo = reactive({
  visible: false,
  query: {},
})
const productionTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
watch(
  () => tableInfo.data,
  (val) => {
    if (val.length) {
      val.forEach((item, index) => {
        item.tableIndex = index + 1
      })
    }
  }
)

watch(
  () => tableInfo.data,
  () => {
    //发票号汇总
    let receiptNumberArr = []
    let receiptSumAmount = 0
    tableInfo.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(calcQty, parseFloat(row.price)),
        unitConvertCoefficient
      )

      if (row.receiptNumber) {
        receiptNumberArr.push(row.receiptNumber)
      }
      if (receiptNumberArr.length) {
        receiptNumberArr = [...new Set(receiptNumberArr)]
      }

      row.receiptSumAmount = proxy.$fn.accMul(
        row.receiptPrice || 0,
        row.receiptCalcQty || 0
      )
      receiptSumAmount = proxy.$fn.accAdd(
        row.receiptSumAmount,
        receiptSumAmount
      )
    })
    formInfo.data['receiptNumber'] = String(receiptNumberArr)
    formInfo.data['receiptSumAmount'] = receiptSumAmount
  },
  {
    deep: true,
  }
)

function receiptNumberChange(val, index) {
  // if(!props.orderId) {
  tableInfo.data[index].receiptCalcQty = !tableInfo.data[index].receiptCalcQty
    ? tableInfo.data[index].qty
    : tableInfo.data[index].receiptCalcQty
  tableInfo.data[index].receiptPrice = !tableInfo.data[index].receiptPrice
    ? tableInfo.data[index].price
    : tableInfo.data[index].receiptPrice
  // }
}

let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
  },

  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'slot',
    permission: !proxy.$permission('receiving:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('receiving:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('receiving:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  defaultPrice: {
    label: '默认价格',
    value: 'defaultPrice',
    type: 'column',
    permission: !proxy.$permission('receiving:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  tem: {
    label: '到货温度',
    value: 'tem',
    type: 'slot',
    hidden: true,
  },
  hum: {
    label: '到货湿度',
    type: 'slot',
    value: 'hum',
    hidden: true,
  },
  packageMarkValue: {
    label: '包装标识',
    value: 'packageMarkValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  identifyMarkValue: {
    label: '确定标识',
    value: 'identifyMarkValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  certificateMarkValue: {
    label: '合格证',
    value: 'certificateMarkValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  appearanceQualityValue: {
    label: '外观质量',
    value: 'appearanceQualityValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  invalidReasonValue: {
    label: '不合格原因值',
    value: 'invalidReasonValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  productionDate: {
    label: '生成日期',
    value: 'productionDate',
    type: 'slot',
    minWidth: '160px',
    hidden: true,
  },
  validityDate: {
    label: '失效日期',
    value: 'validityDate',
    minWidth: '160px',
    type: 'slot',
    hidden: true,
  },
  batchNumber: {
    label: '批号',
    value: 'batchNumber',
    type: 'slot',
    hidden: true,
  },
  receiptNumber: {
    label: '开票号',
    value: 'receiptNumber',
    type: 'slot',
    show: false,
    hidden: true,
  },
  receiptCalcQty: {
    label: '开票数量',
    value: 'receiptCalcQty',
    type: 'slot',
    show: false,
    hidden: true,
  },
  receiptPrice: {
    label: '开票单价',
    value: 'receiptPrice',
    type: 'slot',
    permission: !proxy.$permission('receiving:price'),
    show: false,
    hidden: true,
  },
  receiptSumAmount: {
    label: '开票金额',
    value: 'receiptSumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('receiving:price'),
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
let collapseHeight = ref()
const theResizeObserver = ref()
watch(
  () => collapseHeight.value,
  (val) => {
    if (val >= 340 || val <= 52) {
      proxy.$store.dispatch('app/togglePageTable')
    }
  },
  {
    immediate: true,
    deep: true,
  }
)
function handleResize(entries) {
  collapseHeight.value =
    document.getElementsByClassName('el-collapse')[0].offsetHeight
}
getCustomize()
onMounted(() => {
  proxy.$nextTick(() => {
    theResizeObserver.value = new ResizeObserver(handleResize)
    const theElement = document.getElementsByClassName('el-collapse')[0]
    theResizeObserver.value.observe(theElement)
  })
  //请求默认地址并回填
  getReceiveAddressPage({ isDefault: '1' }).then((resp) => {
    if (resp && resp.success && resp.data[0]) {
      let data = resp.data[0]
      formInfo.data.receiveAddressValue = data.addressValue
      formInfo.data.receiveProvince = data.province
      formInfo.data.receiveCity = data.city
      formInfo.data.receiveCounty = data.county
      formInfo.data.receiveAddress = data.address
      formInfo.data.receivingContacts = data.contacts
      formInfo.data.receivingPhone = data.contactsPhone
    }
  })
})
onBeforeUnmount(() => {
  theResizeObserver.value.disconnect()
})
function changeData(evet, row, index) {
  //批号效期改变更新_id
  let item = tableInfo.data.filter((item, i) => i === index)
  const key =
    item.productId +
    '&' +
    item.batchNumber +
    '&' +
    item.validityDate +
    '&' +
    item.productionDate
  tableInfo.data[index] = {
    ...tableInfo.data[index],
    _id: key,
  }
}
function indexMethod(row) {
  return row.tableIndex
}
function addBatchNumber(row, index) {
  tableInfo.data.splice(index + 1, 0, {
    ...row,
    id: null,
    rowId: proxy.$fn.getUid(),
    // isConsignment: '',
    // isConsignmentValue: '',
    batchNumber: '',
    productionDate: '',
    validityDate: '',
    largeUnitQty: undefined,
    smallUnitQty: undefined,
    calcQty: undefined,
    qty: undefined,
  })
}
function batchHandle() {
  //批量设置发票号
  let receiptNumber = filterInfo.data.receiptNumber
  if (receiptNumber) {
    if (tableInfo.selections.length) {
      tableInfo.selections.forEach((row) => {
        if (
          formInfo.data.isEstimationStockBusiness != 1 &&
          formInfo.data.isConsignBusiness !== '1'
        ) {
          if (formInfo.data.isConsignBusiness === '0') {
            row['receiptNumber'] = receiptNumber
            row['receiptCalcQty'] = proxy.$fn.deepClone(row.qty || 0)
            row['receiptPrice'] = proxy.$fn.deepClone(row.price || 0)
            row['receiptSumAmount'] = proxy.$fn.deepClone(row.sumAmount || 0)
          } else {
            if (row.isConsignment == 0) {
              row['receiptNumber'] = receiptNumber
              row['receiptCalcQty'] = proxy.$fn.deepClone(row.qty || 0)
              row['receiptPrice'] = proxy.$fn.deepClone(row.price || 0)
              row['receiptSumAmount'] = proxy.$fn.deepClone(row.sumAmount || 0)
            }
          }
        }
      })
    } else {
      proxy.$message({
        message: '请选择需批量调发票号的明细！',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    }
  }
}
function openSupplier() {
  // 供应商
  supplierInfo.visible = true
}
function callBackSupplier(row) {
  if (row) {
    formInfo.data['supplierName'] = row.supplierName
    formInfo.data['supplierId'] = row.supplierId
  } else {
    formInfo.data['supplierName'] = ''
    formInfo.data['supplierId'] = ''
  }
  tableInfo.data = []
  scanInfo.query.supplierId = formInfo.data.supplierId
}
//选择部门
function selectPurchDept() {
  selectDeptInfo.visible = true
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.data['purchDeptName'] = row.name
    formInfo.data['purchDeptId'] = row.id
  } else {
    formInfo.data['purchDeptName'] = ''
    formInfo.data['purchDeptId'] = ''
  }
}

function handleResponse(response, file) {
  return file
}
function handleFormEvent(str, val) {
  //寄售 暂估业务 最多只能支持一个 可两个都为否，一个为是  另一个则为否
  if (str === 'isEstimationStockBusiness') {
    if (formInfo.data.isEstimationStockBusiness == 1) {
      formInfo.data.isConsignBusiness = '0'
    }
    if (tableInfo.data.length) {
      tableInfo.data.forEach((row) => {
        if (val === '1') {
          row.isEstimationStockBusiness = '1'
          row.isEstimationStockBusinessValue = '是'
        } else if (val === '0') {
          row.isEstimationStockBusiness = '0'
          row.isEstimationStockBusinessValue = '否'
        }
      })
    }
  } else if (str === 'isConsignBusiness') {
    if (formInfo.data.isConsignBusiness == 1) {
      formInfo.data.isEstimationStockBusiness = 0
    }
  }
}

function changeSelectAll(val, str) {
  if (!val) {
    return
  }
  let obj = {
    package_mark: 'packageMark',
    identify_mark: 'identifyMark',
    certificate_mark: 'certificateMark',
    appearance_quality: 'appearanceQuality',
    invalid_reason: 'invalidReason',
  }
  let option = proxy.$store.state.permission.dict[str]
  let optionItem = option.find((item) => item.code === val)

  tableInfo.data.forEach((row) => {
    row[obj[str] + 'Value'] = optionItem.name
    row[obj[str]] = val
  })
}

function changeNumberTemHum(str) {
  let data = filterInfo.data
  tableInfo.data.forEach((row) => {
    if (row.details && row.details.length) {
      row.details.forEach((item) => {
        item[str] = data[str]
      })
    }
    row[str] = data[str]
  })
}

function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
//数量操作模式 qtyOperateMode：0整数模式，2自动算出小数，1手动输入小数
// 条码类型 code_type：1无码，2系统唯一码，3原厂码，4批次码
function largeMax(row) {
  //原厂码最大为1[0,1]
  if (row.codeType === 3) {
    return 1
  } else {
    return 99999999
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  if ((row.qtyOperateMode === 2 && row.stockQty > 0) || row.codeType === 3) {
    if (e === 1) {
      row.smallUnitQty = 0
    }
  }
  proxy.$nextTick(() => {
    proxy.$refs.tableForm.clearValidate(str)
  })
}
function changeSmall(e, row) {
  if (row.qtyOperateMode === 2) {
    if ((row.codeType === 2 && row.stockQty > 0) || row.codeType === 3) {
      if (e > 0) {
        row.largeUnitQty = 0
      }
    }
  }
}

function onCallBackScanData(stateProduct) {
  let itemIndex = tableInfo.data.findIndex(
    (item) =>
      item.factoryMainCode === stateProduct.data.factoryMainCode &&
      item.factorySubCode === stateProduct.data.factorySubCode
  )
  tableInfo.data.forEach((item, index) => {
    if (index === itemIndex) {
      item.isChoice = true
    } else {
      item.isChoice = false
    }
  })
  if (itemIndex !== -1) {
    proxy.$message({
      message: '重复扫码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }

  if (stateProduct.data.qtyOperateMode === 2) {
    stateProduct.data.largeUnitQty = parseInt(
      stateProduct.data.calcQty / stateProduct.data.unitConvertCoefficient || 1
    )
    stateProduct.data.smallUnitQty = parseInt(
      stateProduct.data.calcQty % stateProduct.data.unitConvertCoefficient || 0
    )
  } else {
    stateProduct.data.largeUnitQty = stateProduct.data.calcQty || 1
    stateProduct.data.smallUnitQty = 0
  }
  stateProduct.data = {
    ...stateProduct.data,
    price: stateProduct.data.price || 0,
    isChoice: true,
    productionDate: stateProduct.data.productionDate || undefined,
    validityDate: stateProduct.data.validityDate || undefined,
    price: stateProduct.data.price || 0,
    receiptQty: stateProduct.data.receiptQty || 0,
    receiptCalcQty: stateProduct.data.receiptCalcQty || 0,
    receiptPrice: stateProduct.data.receiptPrice || 0,
    ...filterInfo.data,
  }
  tableInfo.data.push(stateProduct.data)
}

function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
function openDepotWindow() {
  selectDepotInfo.visible = true
}
function addProduct() {
  productInfo.query.supplierId = formInfo.data.supplierId
  productInfo.query.productIdNotIn = tableInfo.data
    .map((item) => item.productId)
    .toString()
  productInfo.visible = true
}
function selectProduct(rows = []) {
  if (rows.length) {
    rows = generateProductKey(rows)
    rows = rows.map((row) => {
      return {
        price: row.price || 0,
        largeUnitQty: 0,
        qty: 1,
        code: null,
        batchNumber: '',
        productionDate: '',
        validityDate: '',
        productId: row.id,
        rowId: proxy.$fn.getUid(),
        id: null,
        factoryMainCode: row.mainCode,
        factorySubCode: row.subCode,
        defaultSupplierId: row.supplierId,
        defaultSupplierName: row.supplierName,
        defaultSupplierCode: row.supplierCode,
        defaultSupplierPrice: row.price,
        isConsignment: '',
        isConsignmentValue: '',
        receiptQty: row.receiptQty || 0,
        receiptCalcQty: row.receiptCalcQty || 0,
        receiptPrice: row.receiptPrice || 0,
        ...row,
        ...filterInfo.data,
      }
    })
    tableInfo.data = tableInfo.data.concat(rows)
  }
}

function selectDepotCallBack(row) {
  if (row && row.id) {
    formInfo.data.depotName = row.name
    formInfo.data.depotId = row.id
    formInfo.data.deptId = row.deptId
    formInfo.data.deptName = row.deptName
  } else {
    formInfo.data.depotName = ''
    formInfo.data.depotId = ''
    formInfo.data.deptId = ''
    formInfo.data.deptName = ''
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function remove(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.data = tableInfo.data.filter((row) => row !== selectRow)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter(
          (row) => !tableInfo.selections.includes(row)
        )
      })
  }
}
function tableRowClassName({ row }) {
  if (row.isChoice && row.codeType === 3) {
    return 'success-row'
  } else {
    return ''
  }
}

function getDepotsDefaults() {
  let systemConfig = proxy.$store.state.permission.systemConfig
  if (systemConfig.default_receive_depot == 1) {
    //查询默认仓库
    getDepotsDefault().then((resp) => {
      if (resp && resp.success) {
        let data = resp.data
        if (data) {
          formInfo.data.depotName = data.name
          formInfo.data.depotId = data.id
          formInfo.data.deptName = data.deptName
          formInfo.data.deptId = data.deptId
        }
      }
    })
  } else if (systemConfig.default_receive_depot == 2) {
    let depotName = proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
      : ''
    formInfo.data.depotName = depotName
    formInfo.data.depotId = proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
      : ''
    let deptName = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : ''
    formInfo.data.deptName = deptName
    formInfo.data.deptId = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : ''
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let mergeDetails = proxy.$fn
      .deepClone(tableInfo.data)
      .filter((row) => row.qty > 0)
    if (!mergeDetails.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    let arr = mergeDetails.filter((item) => item.price == 0 || !item.price)
    if (arr.length) {
      proxy
        .$confirm(`存在价格为0的数据，是否继续保存?`, '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
        })
        .then(() => {
          realSave(mergeDetails, isSaveAndSubmit)
          return
        })
        .catch(() => {
          return
        })
    } else {
      realSave(mergeDetails, isSaveAndSubmit)
    }
  })
}
function realSave(mergeDetails, isSaveAndSubmit) {
  //校验是否强制批号效期
  let details = generateProductKey(tableInfo.data)
  const needBatchNumberProduct = details
    .filter(
      (detail) =>
        detail.needBatchNumber === 1 &&
        ((!detail.batchNumber && detail.batchNumber !== 0) ||
          !detail.productionDate ||
          !detail.validityDate)
    )
    .map((detail) => detail.commonName)
  if (needBatchNumberProduct.length) {
    proxy.$alert(
      `请输入产品【${needBatchNumberProduct}】的批号效期`,
      '操作提示',
      {
        confirmButtonText: '确定',
      }
    )
    return
  }
  //检验复制行或者新增不允许存在同产品同批号效期
  const _ids = details
    .filter((item) => item.codeType !== 3)
    .map((item) => item._id)
  const _idsSet = new Set(_ids)
  if (_idsSet.size !== _ids.length) {
    //获取重复的_id(key)并且去重
    const filterUnique = (arr) =>
      arr.filter((i) => arr.indexOf(i) !== arr.lastIndexOf(i))
    let arr = Array.from(new Set(filterUnique(_ids)))
    //重复数据
    let repeatDetails = []
    _.uniq(arr).forEach((item) => {
      repeatDetails.push(details.find((i) => i._id === item))
    })
    let repeatCommonNames = repeatDetails.map((item) => {
      if (arr.includes(item._id)) {
        return item.commonName
      }
    })
    proxy.$alert(
      `产品【${repeatCommonNames}】存在相同批号效期产品，请修改`,
      '操作提示',
      {
        confirmButtonText: '确定',
      }
    )
    return
  }
  //同产品 同批号效期 检验 价格、发票号、开票单价 要一致,原厂码
  const _ids1 = details
    .filter((item) => item.codeType === 3)
    .map((item) => item._id)
  //获取重复的_id(key)并且去重
  const filterUnique = (arr) =>
    arr.filter((i) => arr.indexOf(i) !== arr.lastIndexOf(i))
  let arr1 = Array.from(new Set(filterUnique(_ids1)))
  //重复数据
  let repeatDetails1 = []
  tableInfo.data.forEach((item) => {
    if (arr1.includes(item._id)) {
      item._key =
        item.productId +
        '&' +
        item.batchNumber +
        '&' +
        item.validityDate +
        '&' +
        item.productionDate +
        '&' +
        item.price +
        '&' +
        item.receiptNumber +
        '&' +
        item.receiptPrice
      repeatDetails1.push(item)
    }
  })
  let uniqArr = _.uniqBy(repeatDetails1, '_key')
  if (uniqArr.length > arr1.length) {
    let repeatCommonNames1 = repeatDetails1.map((item) => {
      if (arr1.includes(item._id)) {
        return item.commonName
      }
    })
    repeatCommonNames1 = Array.from(new Set(repeatCommonNames1))
    proxy.$alert(
      `产品【${repeatCommonNames1}】存在相同批号效期产品，产品的价格、发票号、开票单价应一致，请修改`,
      '操作提示',
      {
        confirmButtonText: '确定',
      }
    )
    return
  }
  // return
  let receiptErr = []
  let qtyErr = []
  tableInfo.data.forEach((item) => {
    if (
      !(item.receiptPrice && item.receiptCalcQty && item.receiptNumber) &&
      (item.receiptPrice || item.receiptCalcQty || item.receiptNumber)
    ) {
      receiptErr.push(item.commonName)
    }
    if ((item.receiptCalcQty || 0) > item.qty) {
      qtyErr.push(item.commonName)
    }
  })
  if (receiptErr && receiptErr.length) {
    proxy.$message.warning(
      '请输入产品' + String(receiptErr) + '的开票数量、开票单价、开票号'
    )
    return
  }
  if (qtyErr && qtyErr.length) {
    proxy.$message.warning(
      '产品' + String(qtyErr) + '的开票数量应该小于等于收货数量'
    )
    return
  }

  mergeDetails.forEach((item) => {
    item.receiptQty = item.receiptCalcQty
    item.isEstimationStockBusiness = 0
  })
  formInfo.data.isEstimationStockBusiness = 0
  formInfo.data.mergeDetails = proxy.$fn.filterBlacklist(mergeDetails)
  let api =
    isSaveAndSubmit === true ? handAddReceivingsAndSave : handAddReceivings
  validateReceivingOrderNums(formInfo.data).then((_resp) => {
    if (_resp.code === 200) {
      api(formInfo.data).then((resp) => {
        if (resp && resp.success) {
          showDialog.value = false
          emit('returnModify')
        }
      })
    }
  })
}
function returnBank() {
  showDialog.value = false
  emit('returnModify', 'back')
}

function getMain() {
  getReceivingOrderById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data
      formInfo.data.isConsignBusiness =
        formInfo.data.isConsignBusiness === 0
          ? '0'
          : formInfo.data.isConsignBusiness === 1
          ? '1'
          : formInfo.data.isConsignBusiness
      scanInfo.query.supplierId = formInfo.data.supplierId
      getList()
    }
  })
}
function getList() {
  receivingDetailsCustomizeListAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      res.data.forEach((row) => {
        row.key = row.productId + '&'
        row.batchNumber = row.batchNumber || ''
        row.productionDate = row.productionDate || ''
        row.validityDate = row.validityDate || ''
      })
      tableInfo.data = generateProductKey(res.data)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'stockReceivingOrderHandModify-com.slip.spd.entity.vo.stock.ReceivingOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      filterInfo.query.customizeUserVO = data
      if (props.orderId) {
        filterInfo.query.queryMap.orderId.value = props.orderId
        getMain()
      }
      setBusinessDate()
      getDepotsDefaults()
    }
  })
}

//打开选择收货地址窗口
function openReceiveAddressWindow() {
  selectReceiveAddressInfo.visible = true
}
function selectReceiveAddressCallback(data) {
  if (data) {
    formInfo.data.receiveAddressValue = data.addressValue
    formInfo.data.receiveProvince = data.province
    formInfo.data.receiveCity = data.city
    formInfo.data.receiveCounty = data.county
    formInfo.data.receiveAddress = data.address
    formInfo.data.receivingContacts = data.contacts
    formInfo.data.receivingPhone = data.contactsPhone
  }
}
</script>

<style scoped lang="scss"></style>
